package ali_oss

import (
	"bytes"
	"code.byted.org/mobaijie/sender/define"
	"fmt"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/sirupsen/logrus"
	"sync"
)

var initOnce sync.Once
var ossClient *oss.Client
var log = logrus.New()

func InitOssClient() {
	initOnce.Do(func() {
		if ossClient == nil {
			client, err := oss.New(define.EndPoint, define.Key, define.Secret)
			if err != nil {
				log.Errorf("init ali_oss client fail, err: %s", err.Error())
			}
			ossClient = client
		}
	})
}

func GetOssClient() *oss.Client {
	if ossClient == nil {
		panic("should init ali_oss client first")
	}
	return ossClient
}

func UploadImg(stream []byte, fileName string) (error, string) {
	client := GetOssClient()
	bucket, err := client.Bucket(define.Bucket)
	if err != nil {
		log.Errorf("get bucket fail, err: %s", err)
		return err, ""
	}
	err = bucket.PutObject(fileName, bytes.NewReader(stream))
	if err != nil {
		log.Errorf("upload file fail, err: %s", err.Error())
		return err, ""
	}
	return err, fmt.Sprintf("%s%s", define.UrlPrefix, fileName)
}
